package com.github.bdeenyy.asv.util;

import com.github.bdeenyy.asv.model.VectorData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.FileChooser;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;

public class ExcelLoader {
    public ObservableList<VectorData> loadFromExcel() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Excel Files", "*.xls", "*.xlsx"));
        File file = fileChooser.showOpenDialog(null);

        if (file != null) {
            try (Workbook workbook = new XSSFWorkbook(file)) {
                Sheet sheet = workbook.getSheetAt(0);
                ObservableList<VectorData> dataFromFile = FXCollections.observableArrayList();

                for (Row row : sheet) {
                    if (row.getRowNum() == 0) {
                        // Skip header row
                        continue;
                    }
                    Cell nameCell = row.getCell(0);
                    Cell length1Cell = row.getCell(1);
                    Cell length2Cell = row.getCell(2);
                    Cell length3Cell = row.getCell(3);

                    String name = getCellValueAsString(nameCell);
                    double length1 = getCellValueAsDouble(length1Cell);
                    double length2 = getCellValueAsDouble(length2Cell);
                    double length3 = getCellValueAsDouble(length3Cell);

                    VectorData vectorData = new VectorData(name, length1, length2, length3);
                    dataFromFile.add(vectorData);
                }

                return dataFromFile;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return FXCollections.observableArrayList();
    }

    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue();
            case NUMERIC -> Double.toString(cell.getNumericCellValue());
            default -> "";
        };
    }

    private double getCellValueAsDouble(Cell cell) {
        if (cell == null) {
            return 0.0;
        }
        return switch (cell.getCellType()) {
            case NUMERIC -> cell.getNumericCellValue();
            case STRING -> {
                try {
                    yield Double.parseDouble(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    yield 0.0;
                }
            }
            default -> 0.0;
        };
    }
}